﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using Telerik.Web.UI;
using ud_gSDMS.Code_Service;
using System.Linq;
using System.Web.UI;
using System.Text;

namespace ud_gSDMS.testing
{
    public partial class Testing_Manage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private SiteUser _siteUser;
        
        void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (SiteUtils.GetCurrentSiteUser()==null)
                {
                    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                }
                else
                {
                    _siteUser = SiteUtils.GetCurrentSiteUser();

                    if (!Page.IsPostBack)
                    {
                        PopulateLabels();
                        PopulateControls();
                    } 
                }
            }
            catch
            {
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            datFrom_Date.SelectedDate = new DateTime(2000,1,1);
            datTo_Date.SelectedDate = DateTime.Now;

            LoadControl();
            LoadGrid();

            datFrom_Date.SelectedDate = DateTime.Now.AddMonths(-1);
        }

        private void LoadGrid()
        {
            if (_siteUser != null)
            {
                var data = gSDMS_BL.ud_gSDMS_PROJECT_TEST_Search(cboProject_Code.SelectedValue,
                                                                    cboProject_Name.SelectedValue,
                                                                    datFrom_Date.SelectedDate == null ? null : datFrom_Date.SelectedDate.Value.ToString() ,
                                                                    datTo_Date.SelectedDate == null ? null : datTo_Date.SelectedDate.Value.ToString(),
                                                                    cboSender.SelectedValue,
                                                                    cboAssigned_To.SelectedValue, cboStatus.SelectedValue);
                if (ViewState["SortExpression"] != null)
                {
                    var dv = data.DefaultView;
                    dv.Sort = ViewState["SortExpression"].ToString();
                    data = dv.Table;
                }

                grdProject_Test_List.DataSource = data;
                grdProject_Test_List.DataBind();

                ViewState["listProjectTest"] = data;
            }
        }

        private void LoadControl()
        {
            var status = gSDMS_BL.ud_gSDMS_CAT_PROJECT_TEST_STATUS_Lst();
            cboStatus.Items.Add(new RadComboBoxItem("", ""));
            foreach (var p in status)
            {
                cboStatus.Items.Add(new RadComboBoxItem(p.Name, p.CAT_Project_Test_Status_ID.ToString()));
                if (p.Name == "Open")
                    cboStatus.SelectedIndex = cboStatus.Items.Count - 1;
            }

            if (_siteUser != null)
            {
                var projects = gSDMS_BL.ud_gSDMS_PROJECT_GetList();

                cboProject_Code.DataValueField = "Project_ID";
                cboProject_Code.DataTextField = "Code";
                cboProject_Code.DataSource = projects;
                cboProject_Code.DataBind();
                cboProject_Code.Items.Insert(0, new RadComboBoxItem("" , ""));
                cboProject_Code.SelectedValue = "";

                cboProject_Name.DataValueField = "Project_ID";
                cboProject_Name.DataTextField = "Name";
                cboProject_Name.DataSource = projects;
                cboProject_Name.DataBind();
                cboProject_Name.Items.Insert(0, new RadComboBoxItem("", ""));
                cboProject_Name.SelectedValue = "";
                
                var sender = gSDMS_BL.mp_User_Lst("13");
                cboSender.Items.Add(new RadComboBoxItem("", ""));
                foreach (var p in sender)
                {
                    cboSender.Items.Add(new RadComboBoxItem(p.LoginName, p.UserID.ToString()));
                    if (_siteUser.UserId == p.UserID)
                    {
                        btnAdd_New.Visible = true;
                        grdProject_Test_List.Columns[12].Visible = true;
                    }
                    
                }

                cboSender.SelectedValue = "";



                var assign = gSDMS_BL.mp_User_Lst("3");
                cboAssigned_To. Items.Add(new RadComboBoxItem("", ""));
                foreach (var p in assign)
                {
                    cboAssigned_To.Items.Add(new RadComboBoxItem(p.LoginName, p.UserID.ToString()));
                    
                }

                cboAssigned_To.SelectedValue = "";

                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "3"))
                {
                    grdProject_Test_List.Columns[11].Visible = true;
                }
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "13"))
                {
                    grdProject_Test_List.Columns[11].Visible = true;
                    grdProject_Test_List.Columns[12].Visible = true;
                }
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "1"))
                {
                    grdProject_Test_List.Columns[11].Visible = true;
                    grdProject_Test_List.Columns[12].Visible = true;
                    btnAdd_New.Visible = true;
                }

                LoadHidAvailable();
            }
        }

        void LoadHidAvailable()
        {
            if (_siteUser != null)
            {
                if (gSDMS_BL.mp_User_Is_In_Any_Project(_siteUser.UserId))
                {
                    if (gSDMS_BL.ud_gSDMS_PROJECT_TEST_Not_Test_FromUser(_siteUser.UserId).Rows.Count > 0)
                    {
                        hidAvailable.Value = "";
                    }
                    else
                    {
                        hidAvailable.Value = "The projects which you need test had been created all !!";
                    }
                }
                else
                {
                    hidAvailable.Value = "You haven't taken part in any project !!";
                }
            }
            }
        #region event

        private void grdHostngContractDomain_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdProject_Test_List.PageIndex = e.NewPageIndex;
            LoadGrid();
        }
        private void grdHostngContractDomain_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int projectTestID = 0;

            switch (e.CommandName)
            {
                case "delete" :
                    projectTestID = int.Parse(e.CommandArgument.ToString());
                    gSDMS_BL.ud_gSDMS_PROJECT_TEST_Del(projectTestID);
                    LoadHidAvailable();
                    break;
                case "error" :
                    projectTestID = int.Parse(e.CommandArgument.ToString());
                    WebUtils.SetupRedirect(this, SiteRoot + "/gsdmsmodule/testing/Error_Lists.aspx?pageid=9&testid=" + projectTestID);
                    break;
            }
        }

        void grdHostngContractDomain_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            LoadGrid();
        }
        void grdHostngContractDomain_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["Direction"] == null) ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " ASC") ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " DESC") ViewState["Direction"] = " ASC";
            string strSortExp = e.SortExpression + ViewState["Direction"].ToString();
            ViewState["SortExpression"] = strSortExp;
            
            LoadGrid();
        }

        void btnSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            LoadGrid();
        }

        #endregion

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            grdProject_Test_List.PageIndexChanging += grdHostngContractDomain_PageIndexChanging;
            grdProject_Test_List.RowCommand += grdHostngContractDomain_RowCommand;
            grdProject_Test_List.RowDeleting += grdHostngContractDomain_RowDeleting;
            grdProject_Test_List.Sorting += grdHostngContractDomain_Sorting;
            grdProject_Test_List.RowDataBound += new GridViewRowEventHandler(grdProject_Test_List_RowDataBound);
            btnAdd_New.Click += new EventHandler(btnAdd_New_Click);
            btnSearch.Click += btnSearch_Click;

            cboProject_Code.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(cboProject_Code_SelectedIndexChanged);
            cboProject_Name.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(cboProject_Name_SelectedIndexChanged);


            //btnFinish.Click += btnFinish_Click;
            SuppressPageMenu();
        }

        void grdProject_Test_List_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (_siteUser == null) return;
            

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                int projectID = (int)DataBinder.Eval(e.Row.DataItem, "Project_ID");
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "3"))
                {
                    e.Row.FindControl("btn_Edit").Visible = true;
                }

                if (gSDMS_BL.mp_User_Is_In_Project(_siteUser.UserId, projectID) || gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "1"))
                {
                    e.Row.FindControl("btn_Edit").Visible = true;
                    e.Row.FindControl("btn_Delete").Visible = true;
                }
            }
        }


        void btnAdd_New_Click(object sender, EventArgs e)
        {
            if (hidAvailable.Value == "")
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/gsdmsmodule/testing/SendProject.aspx?pageid=9");
            }
               
        }

        void ShowMessagebox(string msg)
        {
            StringBuilder sb = new StringBuilder();

            msg = msg.Replace("\n", "\\n");
            msg = msg.Replace("\"", "'");

            // Use StringBuilder to build up our client slide JavaScript.

            sb.Append("<script type='text/javascript'>");

            sb.Append(@"alert( """ + msg + @""" );");

            sb.Append(@"</script>");

            Response.Write(sb.ToString());
        }

        void cboProject_Name_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            cboProject_Code.SelectedValue = cboProject_Name.SelectedValue;
            
        }

        void cboProject_Code_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            cboProject_Name.SelectedValue = cboProject_Code.SelectedValue;
        }

  

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion
    }
}